package jp.co.technotree.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import jp.co.technotree.common.controll.ApplicationContext;
import jp.co.technotree.common.controll.RequestContext;


public class DBGLog {
	public DBGLog(){

	}

	public static void log(String classname,String method, String message){
		RequestContext requestContext = ApplicationContext.getRequestContext();

		String task=null,action = null,command = null;
		if ( requestContext != null ){
			task = requestContext.getTaskCd();
			action = requestContext.getAction();
			command = requestContext.getCommand();
		}else{
			task="";
			action = "";
			command = "";
		}
		logwrite(task,action,command,classname,method,message);

		task=null;
		action = null;
		command = null;
	}

	public static void fwdebug(String classname,String method, String message){
		RequestContext requestContext = ApplicationContext.getRequestContext();

		String task=null,action = null,command = null;
		if ( requestContext != null ){
			task = requestContext.getTaskCd();
			action = requestContext.getAction();
			command = requestContext.getCommand();
		}else{
			task="";
			action = "";
			command = "";
		}
		logwrite(task,action,command,classname,method,message);

		task=null;
		action = null;
		command = null;
	}

	private static void logwrite(String taskCd,String action,String event,String classname,String method,String message){
		System.out.println("["+taskCd+":"+action+":"+event+"]:"+classname+"."+method+":"+message);
//		System.out.println("会社："+ UserConfig.getUserCode() + "---["+taskCd+":"+action+":"+event+"]:"+classname+"."+method+":"+message);
		//writeFile(action,event,classname,method,message);
	}

	private synchronized static void writeFile(String action,String event,String classname,String method,String message){
		ApplicationContext context = ApplicationContext.getInstance();
		if ( context == null )return;

	    String path = context.getAbsolutePath(context.getConfig("log.path"));

		File file = new File(path+"/"+getLogFileName());
		try {
			FileWriter filewriter = new FileWriter(file, true);
			SimpleDateFormat DF1 = new SimpleDateFormat("MMdd HH:mm:ss.SSS");
			filewriter.write(DF1.format(new Date())+" ["+action+":"+event+"]:"+classname+"."+method+":"+message+"\r\n");
			filewriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String getLogFileName(){
		String fileName;
		SimpleDateFormat DF1 = new SimpleDateFormat("yyyyMMdd");
		fileName = DF1.format(new Date())+".log";

		return fileName;
	}
}
